
import { getInfo, login } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Notification } from 'element-ui'

const user = {
  state: {
    token: getToken(),
    user: {},
    roles: [],
    // 第一次加载菜单时用到
    loadMenus: false
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USER: (state, user) => {
      state.user = user
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_LOAD_MENUS: (state, loadMenus) => {
      state.loadMenus = loadMenus
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      const rememberMe = userInfo.rememberMe
      // const grant_type = 'password'
      // const scope = 'app'
      // const client_id = 'webApp'
      // const client_secret = 'webApp'
      return new Promise((resolve, reject) => {
        //  login(username, password, code, uuid).then(res => {
        // logintoken(username, password, code, uuid, grant_type, scope, client_id, client_secret).then(res => {
        // logintokenfast(username, password, code, uuid, grant_type, scope, client_id, client_secret).then(res => {
        login(username, password, code, uuid).then(res => {
          var resolve1 = resolve
          console.info(res)
          if (res.code) {
            Notification.error({
              title: res.msg,
              duration: 2500
            })
            reject(new Error('xx'))
          } else {
            setToken(res.access_token, rememberMe)
            console.log(getToken())
            commit('SET_TOKEN', res.access_token)

            getInfo().then(res => {
              console.info(res)
              setUserInfo(res.user, commit)
              commit('SET_LOAD_MENUS', true)
              resolve1()
            })
          }

          // // 第一次加载菜单时用到， 具体见 src 目录下的 permission.js
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        getInfo().then(res => {
          console.log(res)
          setUserInfo(res.user, commit)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resolve()
      })
    },

    updateLoadMenus({ commit }) {
      return new Promise((resolve, reject) => {
        commit('SET_LOAD_MENUS', false)
      })
    }
  }
}

export const setUserInfo = (res, commit) => {
  // 如果没有任何权限，则赋予一个默认的权限，避免请求死循环
  if (res.permissions.length === 0) {
    commit('SET_ROLES', ['ROLE_SYSTEM_DEFAULT'])
  } else {
    console.info(res.permissions)
    console.info(res)
    if (res.headImgUrl) {
      res.headImgUrl = res.headImgUrl.indexOf('http') !== -1 ? res.headImgUrl : process.env.VUE_APP_BASE_API + res.headImgUrl
    }
    var arr = []
    res.permissions.forEach(val => {
      arr.push(val)
    })
    console.info(arr)
    commit('SET_ROLES', arr)
  }
  commit('SET_USER', res)
}

export default user
